<template>
  <div class="task-manager">
    <h1 class="title">{{ title }}</h1>

    <div class="task-input">
      <input v-model="newTask" type="text" placeholder="添加新任务..." @keyup.enter="addTask" />
      <button @click="addTask" :disabled="!newTask.trim()">添加</button>
    </div>

    <div class="filters">
      <button
        v-for="filter in filters"
        :key="filter.value"
        @click="currentFilter = filter.value"
        :class="{ active: currentFilter === filter.value }"
      >
        {{ filter.label }} ({{ filteredTasks(filter.value).length }})
      </button>
    </div>

    <div v-if="filteredTasks(currentFilter).length === 0" class="empty-state">
      没有{{ filterLabel }}任务
    </div>

    <TransitionGroup name="task-list" tag="ul" class="task-list">
      <li v-for="task in filteredTasks(currentFilter)" :key="task.id" class="task-item">
        <div class="task-content">
          <input type="checkbox" :checked="task.completed" @change="toggleTaskStatus(task.id)" />
          <span :class="{ 'task-completed': task.completed }" @dblclick="startEditing(task.id)">
            {{ task.text }}
          </span>
          <input
            v-if="editingTaskId === task.id"
            v-model="editingText"
            type="text"
            class="edit-input"
            @blur="saveEdit"
            @keyup.enter="saveEdit"
            @keyup.esc="cancelEdit"
            ref="editInput"
          />
        </div>

        <div class="task-actions">
          <button @click="startEditing(task.id)" class="edit-btn">编辑</button>
          <button @click="deleteTask(task.id)" class="delete-btn">删除</button>
        </div>
      </li>
    </TransitionGroup>

    <div class="task-summary">
      <span>{{ completedCount }} / {{ tasks.length }} 已完成</span>
      <button v-if="completedCount > 0" @click="clearCompleted" class="clear-btn">
        清除已完成
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, watch, nextTick, onMounted } from 'vue'

  // 定义任务类型
  interface Task {
    id: number
    text: string
    completed: boolean
    createdAt: Date
  }

  // 定义过滤器类型
  type FilterType = 'all' | 'active' | 'completed'

  interface FilterOption {
    label: string
    value: FilterType
  }

  const props = defineProps({
    title: {
      type: String,
      default: '任务管理器'
    },
    storageKey: {
      type: String,
      default: 'vue-task-manager'
    }
  })

  // 状态
  const tasks = ref<Task[]>([])
  const newTask = ref('')
  const currentFilter = ref<FilterType>('all')
  const editingTaskId = ref<number | null>(null)
  const editingText = ref('')
  const editInput = ref<HTMLInputElement | null>(null)

  // 过滤器选项
  const filters: FilterOption[] = [
    { label: '所有', value: 'all' },
    { label: '进行中', value: 'active' },
    { label: '已完成', value: 'completed' }
  ]

  // 当前过滤器标签
  const filterLabel = computed(() => {
    switch (currentFilter.value) {
      case 'active':
        return '进行中的'
      case 'completed':
        return '已完成的'
      default:
        return ''
    }
  })

  // 已完成任务计数
  const completedCount = computed(() => tasks.value.filter(task => task.completed).length)

  // 加载任务
  onMounted(() => {
    const storedTasks = localStorage.getItem(props.storageKey)
    if (storedTasks) {
      try {
        const parsedTasks = JSON.parse(storedTasks)
        tasks.value = parsedTasks.map(
          (task: { id: number; text: string; completed: boolean; createdAt: string }) => ({
            ...task,
            createdAt: new Date(task.createdAt)
          })
        )
      } catch (error) {
        console.error('加载任务失败:', error)
        tasks.value = []
      }
    }
  })

  // 监听任务变化保存到本地存储
  watch(
    tasks,
    newTasks => {
      localStorage.setItem(props.storageKey, JSON.stringify(newTasks))
    },
    { deep: true }
  )

  // 根据过滤器筛选任务
  function filteredTasks(filter: FilterType) {
    switch (filter) {
      case 'active':
        return tasks.value.filter(task => !task.completed)
      case 'completed':
        return tasks.value.filter(task => task.completed)
      default:
        return tasks.value
    }
  }

  // 添加任务
  function addTask() {
    const text = newTask.value.trim()
    if (!text) return

    const newId = tasks.value.length > 0 ? Math.max(...tasks.value.map(task => task.id)) + 1 : 1

    tasks.value.push({
      id: newId,
      text,
      completed: false,
      createdAt: new Date()
    })

    newTask.value = ''
  }

  // 删除任务
  function deleteTask(id: number) {
    const index = tasks.value.findIndex(task => task.id === id)
    if (index !== -1) {
      tasks.value.splice(index, 1)
    }
  }

  // 切换任务状态
  function toggleTaskStatus(id: number) {
    const task = tasks.value.find(task => task.id === id)
    if (task) {
      task.completed = !task.completed
    }
  }

  // 开始编辑任务
  function startEditing(id: number) {
    const task = tasks.value.find(task => task.id === id)
    if (task) {
      editingTaskId.value = id
      editingText.value = task.text

      // 使用nextTick确保在DOM更新后再聚焦输入框
      nextTick(() => {
        editInput.value?.focus()
      })
    }
  }

  // 保存编辑
  function saveEdit() {
    if (editingTaskId.value !== null) {
      const task = tasks.value.find(task => task.id === editingTaskId.value)
      if (task && editingText.value.trim()) {
        task.text = editingText.value.trim()
      }
      editingTaskId.value = null
    }
  }

  // 取消编辑
  function cancelEdit() {
    editingTaskId.value = null
  }

  // 清除已完成任务
  function clearCompleted() {
    tasks.value = tasks.value.filter(task => !task.completed)
  }
</script>

<style scoped>
  .task-manager {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    background-color: #f9f9f9;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  }

  .title {
    text-align: center;
    margin-bottom: 20px;
    color: #333;
  }

  .task-input {
    display: flex;
    margin-bottom: 20px;
  }

  .task-input input {
    flex: 1;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px 0 0 4px;
    font-size: 16px;
  }

  .task-input button {
    padding: 10px 15px;
    background-color: #4caf50;
    color: #fff;
    border: 0;
    border-radius: 0 4px 4px 0;
    cursor: pointer;
    font-size: 16px;
  }

  .task-input button:disabled {
    background-color: #ccc;
    cursor: not-allowed;
  }

  .filters {
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
    gap: 10px;
  }

  .filters button {
    padding: 8px 12px;
    background-color: #f1f1f1;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s;
  }

  .filters button.active {
    background-color: #e0e0e0;
    font-weight: bold;
  }

  .empty-state {
    text-align: center;
    padding: 20px;
    color: #999;
    font-style: italic;
  }

  .task-list {
    list-style: none;
    padding: 0;
    margin: 0;
  }

  .task-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 15px;
    background-color: #fff;
    border: 1px solid #eee;
    margin-bottom: 8px;
    border-radius: 4px;
    transition: all 0.3s;
  }

  .task-content {
    display: flex;
    align-items: center;
    flex: 1;
  }

  .task-content input[type='checkbox'] {
    margin-right: 10px;
  }

  .task-completed {
    text-decoration: line-through;
    color: #999;
  }

  .task-actions {
    display: flex;
    gap: 8px;
  }

  .task-actions button {
    padding: 5px 10px;
    border: 0;
    border-radius: 3px;
    cursor: pointer;
    font-size: 12px;
  }

  .edit-btn {
    background-color: #2196f3;
    color: #fff;
  }

  .delete-btn {
    background-color: #f44336;
    color: #fff;
  }

  .edit-input {
    position: absolute;
    width: 60%;
    padding: 8px;
    border: 1px solid #4caf50;
    border-radius: 4px;
  }

  .task-summary {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 15px;
    margin-top: 15px;
    border-top: 1px solid #eee;
  }

  .clear-btn {
    padding: 5px 10px;
    background-color: #ff9800;
    color: #fff;
    border: 0;
    border-radius: 3px;
    cursor: pointer;
  }

  /* Transition styles */
  .task-list-enter-active,
  .task-list-leave-active {
    transition: all 0.3s;
  }

  .task-list-enter-from,
  .task-list-leave-to {
    opacity: 0;
    transform: translateX(30px);
  }

  .task-list-move {
    transition: transform 0.3s;
  }
</style>
